package com.hy.admin.service.impl;

import com.hy.admin.dao.*;
import com.hy.admin.entity.*;
import com.hy.admin.enums.*;
import com.hy.admin.helper.response.AnswerResponse;
import com.hy.admin.service.AnswerService;
import com.hy.admin.service.MessageService;
import com.hy.core.response.ServicesResult;
import com.hy.utils.CommonUtility;
import com.hy.utils.OSSUtil;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class AnswerServiceImpl implements AnswerService {

    @Autowired
    private AnswerDao answerDao;
    @Autowired
    private ImageDao imageDao;
    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private QuestionClickDao questionClickDao;
    @Autowired
    private MessageService messageService;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public ServicesResult<Boolean> add(AnswerEntity answerEntity, Long teacherId, MultipartFile[] files) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (answerEntity == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //校验必传参数
        if (answerEntity.getQuestionId() == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        if (StringUtils.isEmpty(answerEntity.getContent())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，必传参数为空");
            return servicesResult;
        }
        QuestionEntity question = questionDao.selectByPrimaryKey(answerEntity.getQuestionId());
        if(question == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误，问题不存在");
            return servicesResult;
        }
        if(question.getQueState() == EnumQuestionState.ANSWER.getId()){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("问题已回答，请勿重复回答");
            return servicesResult;
        }
        List<String> imageUrlList = new ArrayList<>();
        if (files != null){
            //上传图片至阿里云OSS
            boolean result = true;
            try{
                for(MultipartFile file:files){
                    //获取文件名
                    String fileName = file.getOriginalFilename();
                    String fileType = fileName.substring(fileName.indexOf(".") + 1 , fileName.length());
                    //使用工具类
                    String imagePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(file), fileType);
                    if(imagePath == null || StringUtils.isEmpty(imagePath)){
                        result = false;
                        break;
                    }
                    imageUrlList.add(imagePath);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            if(imageUrlList == null) {
                //第一个文件上传失败
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
            if(!result){//部分图片上传成功
                //图片上传失败---删除上传成功的图片
                OSSUtil.deleteFiles(imageUrlList);
                //删除图片失败---不做处理，每次上传的文件名根据uuid重新生成，对上传失败的文件没有影响
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
        }

        //存入数据库
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        answerEntity.setUuid(uuid);

        Calendar cal = Calendar.getInstance();

        answerEntity.setCreateTime(cal.getTime());
        answerEntity.setUpdateTime(cal.getTime());
        answerEntity.setStatus(EnumStatus.VALID.getId());
        int count = answerDao.insertSelective(answerEntity);
        if(count <= 0){
            //数据插入失败
            if(imageUrlList.size() > 0) {
                //删除上传的图片
                OSSUtil.deleteFiles(imageUrlList);
            }
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("数据插入失败");
            return servicesResult;
        }

        //记录向平台提问的问题由那位教师回答
        if (question.getIsPlatform() == EnumIsPlatform.YES.getId()){
            question.setTeacherId(teacherId);
            question.setUpdateTime(cal.getTime());
            count = questionDao.updateByPrimaryKeySelective(question);
            if(count <= 0){
                //数据插入失败
                if(imageUrlList.size() > 0) {
                    //删除上传的图片
                    OSSUtil.deleteFiles(imageUrlList);
                }
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("数据修改失败");
                throw new Exception("数据修改失败");
            }
        }
        questionDao.changeQueState(answerEntity.getQuestionId(), EnumQuestionState.ANSWER.getId());
        if(imageUrlList.size() > 0) {
            //根据uuid查询问题数据，与图片表做关联
            answerEntity = answerDao.selectByUuid(uuid);
            List<ImageEntity> imageList = new ArrayList<>();
            for (String imageUrl : imageUrlList) {
                ImageEntity image = new ImageEntity();
                image.setImgPath(imageUrl);
                image.setRelatedId(answerEntity.getId());
                image.setRelatedType(EnumImageRelatedType.ANSWER.getId());
                image.setCreateTime(cal.getTime());
                image.setUpdateTime(cal.getTime());
                image.setStatus(EnumStatus.VALID.getId());
                image.setIsDelete(EnumIsDelete.NO.getId());
                imageList.add(image);
            }
            count = imageDao.batchInsert(imageList);
            if (count != imageList.size()) {
                //删除已上传图片
                OSSUtil.deleteFiles(imageUrlList);
                //插入失败，启动事务回滚
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("图片插入失败");
                throw new Exception("插入图片失败");
            }
        }
        //推送至提问家长的手机
        MemberEntity member = memberDao.selectById(question.getMemberId());
        if(member!= null && StringUtils.isNotBlank(member.getDeviceToken())){
            messageService.addMessageForOne(member.getId(), member.getDeviceToken(), member.getAliDeviceId(), "您提出的问题已被教师回答，请注意查看！", "提问已回答");
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<AnswerResponse> show(Long questionId, Long memberId) {
        ServicesResult<AnswerResponse> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (questionId == null || questionId < 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        //查询问题详情
        AnswerEntity answerEntity = answerDao.selectByQueId(questionId);
        if(answerEntity == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求参数有误");
            return servicesResult;
        }
        //如用户首次查看答案，增加问题点击量,仅限免费问题
        if (answerEntity.getYangCoin() == 0 && memberId != null && memberId > 0) {
            int count = questionClickDao.selectCountByQIdAndMId(questionId, memberId);
            if(count == 0){
                //新增用户点击数据
                QuestionClickEntity queClick = new QuestionClickEntity();
                queClick.setCreateTime(new Date());
                queClick.setMemberId(memberId);
                queClick.setQuestionId(questionId);
                queClick.setStatus(EnumStatus.VALID.getId());
                count = questionClickDao.insertSelective(queClick);
                if(count > 0){
                    //增加点击量
                    questionDao.updateClickNum(questionId);
                }
            }
        }
        //查询问题关联图片
        List<String> imageList = imageDao.selectByRelatedIdAndType(answerEntity.getId(), EnumImageRelatedType.ANSWER.getId());
        //修改答案查看状态
//        QuestionEntity question = questionDao.selectByPrimaryKey(answerEntity.getQuestionId());
//        if(question.getQueState() == EnumQuestionState.ANSWER.getId()) {
//            questionDao.changeQueState(answerEntity.getQuestionId(), EnumQuestionState.CHECK.getId());
//        }
        //处理返回数据
        AnswerResponse answerResponse = new AnswerResponse();
        answerResponse.setContent(answerEntity.getContent());
        answerResponse.setYangCoin(answerEntity.getYangCoin());
        if(imageList != null && imageList.size() > 0){
            answerResponse.setImageList(imageList);
        }
        //查询教师姓名
        QuestionEntity question = questionDao.selectByPrimaryKey(answerEntity.getQuestionId());
        MemberEntity member = memberDao.selectById(question.getTeacherId());
        if(member != null){
            answerResponse.setNickName(member.getNickName());
        }
        servicesResult.setResult(answerResponse);
        return servicesResult;
    }


}
